﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Graficador de Ventas</title>
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/jquery.js"></script>
    <script src="Scripts/jquery.validate.js"></script>
    <script src="Scripts/jquery-ui-1.10.3.custom.js"></script>
    <script src="Scripts/Graph.js"></script>
    <link href="CSS/smoothness/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <link href="CSS/Style.css" rel="stylesheet" />
</head>
<body>
    <script>
        var formDialogValidator = "";
        $(document).ready(function () {
            $("#form1").validate({
                onsubmit: false
            });
            formDialogValidator = $('#form2').validate({
                onsubmit: false
            });
            $.validator.addMethod("checkMoney", function (value, element) {
                var regex = new RegExp(/^\$?[0-9]+(,[0-9]{3})*(\.[0-9]{2})?$/);
                return regex.test(value);
            }, "Favor colocar el formato adecuado ej: 4.50");//^[0-9]{2}/[0-9]{2}/[0-9]{4}?$
            $.validator.addMethod("dateRange", function (value, element) {
                var regex = new RegExp(/^\$?[0-9]{2}[/][0-9]{2}[/][0-9]{4}?$/);
                return regex.test(value);
            }, "Favor colocar el formato adecuado ej: mm/dd/yyyy");
            $('.validationGroup .causesValidation').click(ValidateAndSubmit);
            $('.validationGroup :text').keydown(function (evt) {
                // Only execute validation if the key pressed was enter.
                if (evt.keyCode == 13) {
                    ValidateAndSubmit(evt);
                }
            });
            $('.validationGroupDialog :text').keydown(function (evt) {
                // Only execute validation if the key pressed was enter.
                if (evt.keyCode == 13) {
                    ValidateAndSubmitDialog(evt);
                }
            });
            $('#accordion').accordion();
            $('#btnBarras').button();
            $('#btnTortas').button();
            $('#btnLineas').button();
            $('#' + '<%= btnCliente.ClientID %>').button();
            $('#' + '<%= btnProducto.ClientID %>').button();
            $('#' + '<%= btnVenta.ClientID %>').button();
            $('#dialogCanvas').dialog({
                autoOpen: false,
                height: 600,
                width: 1050,
                modal: true,
                buttons: {
                    "Cerrar Canvas": function () {
                        resetValues();
                        $(this).dialog('close');
                    }
                },
                close: function () {
                    resetValues();
                }
            });
            $('#' + '<%= txtVenta.ClientID %>').datepicker();
            $("#dtStart").datepicker({
                defaultDate: "+1w",
                changeMonth: true,
                numberOfMonths: 3,
                onClose: function (selectedDate) {
                    $("#dtEnd").datepicker("option", "minDate", selectedDate);
                }
            });
            $("#dtEnd").datepicker({
                defaultDate: "+1w",
                changeMonth: true,
                numberOfMonths: 3,
                onClose: function (selectedDate) {
                    $("#dtStart").datepicker("option", "maxDate", selectedDate);
                }
            });

            $('#dialogDateRange').dialog({
                autoOpen: false,
                height: 400,
                width: 600,
                modal: true,
                buttons: {
                    "Generar Gráfico": function (evt) {

                        ValidateAndSubmitDialog(evt);
                        var validity = $('#valid').val();
                        if (validity != "0") {
                            openCanvas();
                            $(this).dialog('close');
                        }
                    }
                },
                close: function () {
                    resetValues();
                    formDialogValidator.resetForm();
                },
                open: function () {
                    $('#comboAClients').empty();
                    getAvailableClients();
                    //$(this).append('#form1');
                }
            });

            $("#btnBarras").click(function () {
                $('#hflag').val('0');
                $('#dialogDateRange').dialog('open');
            });
            $("#btnTortas").click(function () {
                $('#hflag').val('1');
                $('#dialogDateRange').dialog('open');
            });
            $("#btnLineas").click(function () {
                $('#hflag').val('2');
                $('#dialogDateRange').dialog('open');
            });
        });

        function ValidateAndSubmit(evt) {
            var $group = $(evt.currentTarget).parents('.validationGroup');

            var isValid = true;

            $group.find(':input').each(function (i, item) {
                if (!$(item).valid())
                    isValid = false;
            });

            if (!isValid)
                evt.preventDefault();
        }

        function ValidateAndSubmitDialog(evt) {
            //var $group = $(evt.currentTarget).parents('.validationGroupDialog');

            var isValid = true;

            $('#FieldsetValid').find(':input').each(function (i, item) {
                if (!$(item).valid())
                    isValid = false;
            });

            if (!isValid) {
                $('#valid').val("0");
            } else {
                $('#valid').val("1");
            }

        }

        function calculateSale() {
            var parametros = {
                productoID: $('#' + '<%= comboProducto.ClientID %>').val()
            };
            var url = "Index.aspx/UpdatePrice";
            var paramString = JSON.stringify(parametros);
            var result = '';
            $.ajax({
                url: url,
                async: false,
                data: paramString,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    var result = data.d;
                    $('#' + '<%= txtPrecio.ClientID %>').val(result);
                },
                error: function (data) {
                    alert('something went wrong');
                }
            });
        }

        function getAvailableClients() {
            var parametros = {
            };
            var url = "Index.aspx/GetAvailableClients";
            var paramString = JSON.stringify(parametros);
            var result = '';
            $.ajax({
                url: url,
                async: false,
                data: paramString,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    var result = data.d;//comboAClients
                    var select = $('#comboAClients');
                    for (var i = 0; i < result.length; i++) {
                        select.append('<option value="' + result[i].iCliente_id + '">' + result[i].sCliente_nm + '</option>');
                    }
                },
                error: function (data) {
                    alert('something went wrong');
                }
            });
        }

        function openCanvas() {
            $('#listProductos').empty();
            var selectClient = $('#comboAClients').val();
            if (selectClient != '0') {
                $("#graph").renderCanvas({
                    type: $('#hflag').val(),
                    dialog: 'dialogCanvas',
                    ulProducts: 'listProductos',
                    dtStart: $('#dtStart').val(),
                    dtEnd: $('#dtEnd').val(),
                    clienteID: selectClient
                });
            } else {
                $("#graph").renderCanvas({
                    type: $('#hflag').val(),
                    dialog: 'dialogCanvas',
                    ulProducts: 'listProductos',
                    dtStart: $('#dtStart').val(),
                    dtEnd: $('#dtEnd').val()
                });
            }
        }
        function resetValues() {
            $('#dtStart').val('');
            $('#dtEnd').val('');
            $('#hflag').val('');
        }
    </script>
    <form id="form1" runat="server">
        <div id="accordion">
            <h3>Graficador de Ventas</h3>
            <div>
                <input type="hidden" id="hflag" value="" />
                <input type="button" class="buttons" id="btnBarras" value="Gr&#225;fico de Barras" />
                <input type="button" class="buttons" id="btnTortas" value="Gr&#225;fico de Tortas" />
                <input type="button" class="buttons" id="btnLineas" value="Gr&#225;fico de Lineas" />
            </div>
            <h3>Formulario para Clientes</h3>
            <div>
                <fieldset class="validationGroup">
                    <legend>Registro de Cliente</legend>
                    <span>Nombre del Cliente</span><br />
                    <asp:TextBox class="buttons" ID="txtCliente" runat="server" minlength="2" required="required"></asp:TextBox><br />
                    <asp:Button class="buttons" ID="btnCliente" runat="server" Text="Registrar Cliente" CssClass="causesValidation" OnClick="btnCliente_Click" />
                </fieldset>
            </div>
            <h3>Formulario para Producto</h3>
            <div>
                <fieldset class="validationGroup">
                    <legend>Registro de Producto</legend>
                    <span>Descripci&#243;n del Producto</span><br />
                    <asp:TextBox class="buttons" ID="txtProducto" runat="server" minlength="5" required="required"></asp:TextBox><br />
                    <span>Costo del Producto</span><br />
                    <asp:TextBox class="buttons" ID="txtProductoCosto" runat="server" required="required" CssClass="checkMoney"></asp:TextBox><br />
                    <asp:Button class="buttons" ID="btnProducto" runat="server" Text="Registrar Producto" CssClass="causesValidation" OnClick="btnProducto_Click" />
                </fieldset>
            </div>
            <h3>Formulario de Ventas</h3>
            <div>
                <fieldset class="validationGroup">
                    <legend>Registro de Venta</legend>
                    <span>Fecha de Venta</span><br />
                    <asp:TextBox ID="txtVenta" runat="server" CssClass="buttons date dateRange" required="required"></asp:TextBox><br />
                    <span>Producto</span><br />
                    <asp:DropDownList ID="comboProducto" runat="server" onchange="calculateSale();"></asp:DropDownList><br />
                    <span>Precio de Venta</span><br />
                    <asp:TextBox class="buttons" ID="txtPrecio" runat="server" ReadOnly="true" CssClass="checkMoney"></asp:TextBox><br />
                    <span>Cliente</span><br />
                    <asp:DropDownList ID="comboCliente" runat="server"></asp:DropDownList><br />
                    <asp:Button class="buttons" ID="btnVenta" runat="server" Text="Registrar Venta" OnClick="btnVenta_Click" />
                </fieldset>
            </div>
        </div>
        <div>
            <asp:Button ID="btnRefresh" Text="Refresh" runat="server" OnClick="btnRefresh_Click" />
        </div>
        <div id="dialogCanvas" title="Gr&#225;fico">
            <div>
                <canvas id="graph" width="1000" height="430"></canvas>
            </div>
            <ul id="listProductos"></ul>
        </div>
    </form>
    <div id="dialogDateRange">
        <div>
            <input type="hidden" id="valid" value="0" />
            <fieldset id="FieldsetValid" class="validationGroupDialog">
                <legend>Fechas</legend>
                <form id="form2">
                    <p>Fecha Inicio</p>
                    <input id="dtStart" class="dateRange date" required="required" value="" />
                    <p>Fecha Final</p>
                    <input id="dtEnd" class="dateRange date" required="required" value="" />
                    <p>Cliente</p>
                    <select id="comboAClients"></select>
                </form>
            </fieldset>
        </div>
    </div>
</body>
</html>
